import { Component, OnInit, Input } from '@angular/core';
import { TabComponent } from '../tab-details';
import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http';
import { TreeNode, ConfirmationService, DialogService } from 'primeng/api';
import { MediaUploadComponent } from './media-upload.component';
import { MdlDialogService } from '@angular-mdl/core';

@Component({
    templateUrl: './tab-media.component.html',
    styleUrls: ['./tab-media.component.scss']
})
export class TabMediaComponent implements OnInit, TabComponent {
    @Input() data: any;
    medias: any[] = [];
    currentIndex: number = 0;
    currentMedia: any;
    videoPlayers: any[] = [];

    mediaTree: TreeNode[] = [];
    selectedMedia: any;

    loading: boolean = true;
    nodeClickFlag: boolean = false;
    constructor(private http: HttpClient,
        private dialogService: DialogService,
        private mdlDialogService: MdlDialogService) { }

    ngOnInit() {
        this.renderTree();
    }

    ngOnDestroy() {
        this.videoPlayers.forEach(player => player.dispose());
    }

    /**文件上传 */
    upload() {
        const dialog = this.dialogService.open(MediaUploadComponent, {
            header: '请选择要上传的附件',
            width: '850px',
            data: {
                'rowData': this.data,
                'systemUrl': this.data.systemUrl
            },
            contentStyle: { "height": "550px", "overflow": "auto" }
        });
        dialog.onClose.subscribe(data => data && this.renderTree());
    }

    /** 文件选择 */
    nodeSelect($event) {
        let i = 0;
        this.medias.forEach((element, idx) => {
            if (element.id == $event.node['id'] + '') {
                i = idx;
                return;
            }
        });
        while (i < this.currentIndex) {
            setTimeout(function () { $(".swiper-button-prev").click(); }, 300);
            i++;
        }
        while (i > this.currentIndex) {
            setTimeout(function () { $(".swiper-button-next").click(); }, 300);
            i--;
        }
    }

    /** 文件移除 */
    delete() {
        this.mdlDialogService.confirm('您确定要删除文件《' + this.currentMedia.name + '》吗？', '取消', '确定').subscribe(data => this.http.get('/' + this.data.systemUrl + '/api/tab/media/delete?mediaId=' + this.currentMedia.id).subscribe(data => this.renderTree()));
    }

    /** 文件下载 */
    download() {
        var form = $('<form></form>').attr('action', '/media/api/storage/download').attr('method', 'post');
        form.append($('<input></input>').attr('type', 'hidden').attr('name', 'path').attr('value', this.currentMedia.src));
        form.appendTo('body').submit().remove();
    }

    /** 文件翻页 **/
    pervNext(type) {
        this.currentIndex += type;
        this.currentMedia = this.medias[this.currentIndex];
        $('.swiper-lazy-preloader').fadeIn(500).fadeOut(1000);
        if (this.currentMedia.type == 'WORD' || this.currentMedia.type == 'PDF') {
            //WORD PDF
            $("#pdfConcent-" + this.currentMedia.id).hide();
            $('.swiper-lazy-preloader').fadeIn(500);
            this.http.get('/' + this.data.systemUrl + '/api/tab/media/showpdf?path=' + encodeURI(this.currentMedia.src)).subscribe(data => {
                $('.swiper-lazy-preloader').fadeOut(1500);
                var pdfData = atob(data['data']['pdfContent']); //$.base64.
                var uint8Array = new Uint8Array(pdfData.length);
                for (var i = 0; i < pdfData.length; i++) {
                    uint8Array[i] = pdfData.charCodeAt(i);
                }
                window['printPdfContent'] = { 'pdfName': this.currentMedia.name, 'pdfContent': uint8Array };
                $("#pdfConcent-" + this.currentMedia.id).attr("src", "/assets/other/pdfjs/viewer.html").ready();
                $("#pdfConcent-" + this.currentMedia.id).fadeIn(500);
            });
        } else if (this.currentMedia.type == 'VIDEO') {
            //视频多媒体
            let videoPlayer = videojs('video-' + this.currentMedia.id);
            let mediaSrc = "/media/api/storage/download?path=" + encodeURI(this.currentMedia.src);
            videoPlayer.ready(function () {
                var obj = this;
                obj.src([{ type: "video/mp4", src: mediaSrc }]);
                obj.load();
            });
            this.videoPlayers.push(videoPlayer)
        }
    };

    /** 重新加载树 */
    renderTree() {
        this.loading = true;
        this.mediaTree = [];
        this.http.get('/' + this.data.systemUrl + '/api/tab/media/listtree?recId=' + this.data.recId + '&bizId='+ this.data.bizId).subscribe(data => {
            this.loading = false;
            this.mediaTree = data['data'];
            let temp = [];
            data['data'].forEach(element => {
                if (element.children && element.children.length > 0) {
                    element.children.forEach(child => {
                        temp.push({ id: child['id'], name: child.label, src: child['data']['filePath'], type: child['data']['type'] });
                    })
                }
            });
            this.medias = temp;
            this.currentMedia = this.medias[this.currentIndex];
            this.videoPlayers.forEach(player => player.dispose());
            setTimeout(() => this.renderSwiper(), 1000);
        });
    }

    /** 渲染多媒体组件 */
    renderSwiper() {
        let swiper = new Swiper('.swiper-container', {
            zoom: true,
            lazy: true,
            navigation: {
                nextEl: '.swiper-button-next',
                prevEl: '.swiper-button-prev',
            }
        });
    }
}
